<template>
  <view class="chat-container">
    <!-- 聊天消息列表 -->
    <scroll-view class="chat-messages" scroll-y="true">
      <view class="message-list">
        <!-- 欢迎消息 -->
        <view v-if="messages.length === 0" class="welcome-message">
          <view class="welcome-icon">🤖</view>
          <view class="welcome-text">你好！我是RAG AI助手</view>
          <view class="welcome-desc">请上传一些文档，然后我就可以回答你的问题了</view>
        </view>

        <!-- 消息列表 -->
        <view 
          v-for="(message, index) in messages" 
          :key="index"
          class="message-item"
          :class="message.type"
        >
          <view class="message-avatar">
            <text v-if="message.type === 'user'">👤</text>
            <text v-else>🤖</text>
          </view>
          <view class="message-content">
            <view class="message-text">{{ message.content }}</view>
            <view class="message-time">{{ formatTime(message.time) }}</view>
          </view>
        </view>

        <!-- 加载状态 -->
        <view v-if="isLoading" class="loading-message">
          <view class="loading-avatar">🤖</view>
          <view class="loading-content">
            <view class="loading-text">AI正在思考中...</view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 输入区域 -->
    <view class="chat-input-area">
      <view class="input-container">
        <textarea
          class="message-input"
          v-model="inputMessage"
          placeholder="输入你的问题..."
          :disabled="isLoading"
          :maxlength="500"
          auto-height
          @confirm="sendMessage"
        />
        <button 
          class="send-btn" 
          @click="sendMessage"
          :disabled="!inputMessage.trim() || isLoading"
        >
          <text class="send-icon">📤</text>
        </button>
      </view>
      
      <!-- 快捷操作 -->
      <view class="quick-actions">
        <button class="quick-btn" @click="clearHistory">
          <text class="quick-icon">🗑️</text>
          <text>清空历史</text>
        </button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      messages: [],
      inputMessage: '',
      isLoading: false,
      sessionId: 'uniapp-session-' + Date.now(),
      userInfo: null
    }
  },
  onLoad() {
    this.loadUserInfo()
    this.loadChatHistory()
  },
  methods: {
    // 加载用户信息
    loadUserInfo() {
      const userInfo = uni.getStorageSync('userInfo')
      if (userInfo) {
        this.userInfo = userInfo
      } else {
        // 如果没有用户信息，跳转到登录页
        uni.redirectTo({
          url: '/pages/auth/login'
        })
      }
    },

    // 加载聊天历史
    async loadChatHistory() {
      try {
        const token = uni.getStorageSync('token')
        const response = await uni.request({
          url: 'http://localhost:5000/api/chat/history',
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          },
          data: {
            sessionId: this.sessionId
          }
        })
        if (response.statusCode === 200 && response.data.success) {
          this.messages = response.data.data.map(msg => ({
            type: msg.isUser ? 'user' : 'ai',
            content: msg.content,
            time: new Date(msg.timestamp)
          }))
        }
      } catch (error) {
        console.error('加载聊天历史失败:', error)
      }
    },

    // 发送消息
    async sendMessage() {
      const message = this.inputMessage.trim()
      if (!message || this.isLoading) return

      // 添加用户消息
      this.addMessage('user', message)
      this.inputMessage = ''
      this.isLoading = true

      try {
        const token = uni.getStorageSync('token')
        const response = await uni.request({
          url: 'http://localhost:5000/api/chat/ask',
          method: 'POST',
          header: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          data: {
            question: message,
            sessionId: this.sessionId
          }
        })

        if (response.statusCode === 200 && response.data.success) {
          const data = response.data.data
          this.addMessage('ai', data.answer)
        } else {
          this.addMessage('ai', '抱歉，我无法回答这个问题，请稍后再试。')
        }
      } catch (error) {
        console.error('发送消息失败:', error)
        this.addMessage('ai', '网络错误，请检查连接后重试。')
      } finally {
        this.isLoading = false
      }
    },

    // 添加消息
    addMessage(type, content) {
      this.messages.push({
        type,
        content,
        time: new Date()
      })
      this.scrollToBottom()
    },

    // 滚动到底部
    scrollToBottom() {
      this.$nextTick(() => {
        const query = uni.createSelectorQuery().in(this)
        query.select('.message-list').boundingClientRect(data => {
          if (data) {
            // 滚动到底部
          }
        }).exec()
      })
    },

    // 格式化时间
    formatTime(time) {
      const now = new Date()
      const diff = now - time
      const minutes = Math.floor(diff / 60000)
      const hours = Math.floor(diff / 3600000)
      const days = Math.floor(diff / 86400000)

      if (minutes < 1) return '刚刚'
      if (minutes < 60) return `${minutes}分钟前`
      if (hours < 24) return `${hours}小时前`
      if (days < 7) return `${days}天前`
      
      return time.toLocaleDateString()
    },

    // 清空历史
    clearHistory() {
      uni.showModal({
        title: '确认清空',
        content: '确定要清空所有聊天记录吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const token = uni.getStorageSync('token')
              await uni.request({
                url: 'http://localhost:5000/api/chat/history',
                method: 'DELETE',
                header: {
                  'Authorization': `Bearer ${token}`
                },
                data: {
                  sessionId: this.sessionId
                }
              })
              this.messages = []
              uni.showToast({
                title: '已清空历史',
                icon: 'success'
              })
            } catch (error) {
              uni.showToast({
                title: '清空失败',
                icon: 'none'
              })
            }
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f5f5;
}

.chat-messages {
  flex: 1;
  padding: 20rpx;
}

.message-list {
  padding-bottom: 20rpx;
}

.welcome-message {
  text-align: center;
  padding: 100rpx 40rpx;
  background: white;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
}

.welcome-icon {
  font-size: 80rpx;
  margin-bottom: 20rpx;
}

.welcome-text {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.welcome-desc {
  font-size: 28rpx;
  color: #666;
}

.message-item {
  display: flex;
  margin-bottom: 30rpx;
  align-items: flex-start;
}

.message-item.user {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: #667eea;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40rpx;
  margin: 0 20rpx;
}

.message-item.user .message-avatar {
  background: #38a169;
}

.message-content {
  flex: 1;
  max-width: 70%;
}

.message-text {
  background: white;
  padding: 20rpx;
  border-radius: 20rpx;
  font-size: 28rpx;
  color: #333;
  line-height: 1.5;
  word-wrap: break-word;
}

.message-item.user .message-text {
  background: #667eea;
  color: white;
}

.message-time {
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
  text-align: center;
}

.message-item.user .message-time {
  text-align: right;
}

.loading-message {
  display: flex;
  margin-bottom: 30rpx;
  align-items: flex-start;
}

.loading-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: #667eea;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40rpx;
  margin-right: 20rpx;
}

.loading-content {
  flex: 1;
  max-width: 70%;
}

.loading-text {
  font-size: 24rpx;
  color: #666;
}

.chat-input-area {
  background: white;
  border-top: 1rpx solid #eee;
  padding: 20rpx;
}

.input-container {
  display: flex;
  align-items: flex-end;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.message-input {
  flex: 1;
  background: #f8f9fa;
  border-radius: 25rpx;
  padding: 20rpx;
  font-size: 28rpx;
  min-height: 80rpx;
  max-height: 200rpx;
}

.send-btn {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: #667eea;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.send-btn:disabled {
  background: #ccc;
}

.send-icon {
  font-size: 36rpx;
  color: white;
}

.quick-actions {
  display: flex;
  gap: 20rpx;
}

.quick-btn {
  flex: 1;
  background: #f8f9fa;
  border: 1rpx solid #eee;
  border-radius: 10rpx;
  padding: 15rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
}

.quick-icon {
  font-size: 24rpx;
}
</style> 